<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\notify\gateway;

use app\common\library\InviteCode;
use app\common\manager\MatchManager;
use app\common\manager\UserAccountManager;
use app\common\model\Member;
use app\common\model\Order;
use app\common\model\PayLog;
use app\common\model\SignUp;
use app\common\model\UserAccount;
use app\common\model\UserCoupon;
use think\Db;
use think\Exception;

class Match
{
    public function dealWith($response,$isTrans=true)
    {
        //file_put_contents('callback.log','dealwith response:'.json_encode($response),FILE_APPEND);
        //file_put_contents('callback.log','response type:'.gettype($response),FILE_APPEND);
        if ($isTrans)
            Db::startTrans();
        try {

            $response = json_decode(json_encode($response),true);

            //file_put_contents('callback.log','response type:'.gettype($response),FILE_APPEND);

            //file_put_contents('callback.log','response out_trade_no:'.$response['out_trade_no'],FILE_APPEND);
            if (!$orderInfo = Order::where('order',$response['out_trade_no'])->find()){
                throw new Exception('当前记录不存在');
            }

            if ($orderInfo['pay_state'] != Order::PAY_STATE_INIT){
                throw new Exception('当前订单已处理');
            }

            if (!$relationInfo = \app\common\model\Match::where('m_id',$orderInfo['relation_id'])->find()) {
                throw new Exception('关联信息不存在');
            }
            $extend_param = [];
            if ($orderInfo['extend_param']){
                $extend_param = unserialize($orderInfo['extend_param']);
            }
            if ($response['result_code'] == 'SUCCESS') {

                //file_put_contents('callback.log','result_code:'.$response['result_code'],FILE_APPEND);
                if(!Order::update([
                    'trilateral_pay_order'=>$response['transaction_id'],
                    'pay_date'=>strtotime($response['time_end']),
                    'up_date'=>time(),
                    'pay_state'=>Order::PAY_STATE_SUCCESS
                ],['po_id'=>$orderInfo['po_id']])){
                    //file_put_contents('callback.log','update order fail',FILE_APPEND);
                    throw new Exception('订单更新失败');
                }

                //file_put_contents('callback.log','订单更新成功',FILE_APPEND);
                if(!PayLog::update(['processed'=>PayLog::PROCESSED_STATUS_YES,'update_time'=>time()],['order'=>$response['out_trade_no']])){
                    //file_put_contents('callback.log','订单日志更新失败',FILE_APPEND);
                    throw new Exception('订单日志更新失败');
                }
                //file_put_contents('callback.log','订单日志更新成功',FILE_APPEND);

                $upgradeResult = UserAccountManager::LevelUpgrade($orderInfo['user_id'],'upgrade',false);
                if ($upgradeResult['code']!=UserAccountManager::$successCode){
                    throw new Exception($upgradeResult['message']);
                }

                if (!UserAccount::where(['user_id'=>$orderInfo['user_id']])->update([
                    'consumed_money'=>Db::raw('consumed_money + '.$orderInfo['real_money']),
                    'join_count'=>Db::raw('join_count + 1'),
                    'match_count'=>Db::raw('match_count + 1'),
                    'version'=>Db::raw('version + 1')
                ])) {
                    //file_put_contents('callback.log','账户消费金额累加失败',FILE_APPEND);
                    throw new Exception('账户消费金额累加失败');
                }
                //file_put_contents('callback.log','账户消费金额累加成功',FILE_APPEND);
                $specialResult = MatchManager::specialModify($orderInfo['relation_id'],false);
                if ($specialResult['code']!=MatchManager::$successCode){
                    //file_put_contents('callback.log','specialModify:'.json_encode($specialResult),FILE_APPEND);
                    throw new Exception($specialResult['message']);
                }

                if ($orderInfo['user_coupon_id'] && $orderInfo['pref_money'] > 0){

                    if (!UserCoupon::where('id', $orderInfo['user_coupon_id'])->update(['block' => UserCoupon::BLOCK_NO,'status'=>UserCoupon::STATUS_USED,'update_time'=>time()])){
                        throw new Exception('优惠券使用失败，请稍后再试');
                    }
                }
                //file_put_contents('callback.log','特殊更新成功',FILE_APPEND);
                $inviteCode = new InviteCode();
                $invite = $inviteCode->enCode();
                $signInfo = SignUp::where('id',$extend_param['signId'])->find();
                $matchJoiner = [
                    'match_id'=>$orderInfo['relation_id'],
                    'user_id'=>$orderInfo['user_id'],
                    'order_id'=>$orderInfo['po_id'],
                    'verify_code'=>$invite,
                    'real_name'=>$signInfo['real_name'],
                    'mobile'=>$signInfo['mobile'],
                    'state'=>Member::STATE_SUCCESS,
                    'pay_state'=>Member::PAY_STATE_SUCCESS,
                    'sign_id'=>$signInfo['id'],
                    'backend_system'=>Member::BACKEND_SYSTEM_NO,
                    'create_time'=>time(),
                    'update_time'=>time()
                ];
                $joinerResult = MatchManager::MatchJoinerInsert($orderInfo['relation_id'],$matchJoiner,false);
                if ($joinerResult['code']!=MatchManager::$successCode){
                    throw new Exception('赛事人员信息创建失败，订单取消');
                }
                //file_put_contents('callback.log','组队人员信息创建成功',FILE_APPEND);

            }

            if ($isTrans)
                Db::commit();
            return ['code'=>1,'message'=>'success'];
        }catch (Exception $exception){
            file_put_contents('callback.log',$exception->getMessage().$exception->getLine().PHP_EOL,FILE_APPEND);
            if ($isTrans)
                Db::rollback();
            return ['code'=>0,'message'=>$exception->getMessage()];
        }
    }
}